package com.sh.data.engine.job.admin.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.data.engine.job.admin.core.model.XxlJobLogGlue;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.stream.Collectors;

/**
 * job log for glue
 *
 * @author xuxueli 2016-5-19 18:04:56
 */
@Mapper
public interface XxlJobLogGlueDao extends BaseMapper<XxlJobLogGlue> {

    default int save(XxlJobLogGlue xxlJobLogGlue) {
        return this.insert(xxlJobLogGlue);
    }

    default List<XxlJobLogGlue> findByJobId(int jobId) {
        LambdaQueryWrapper<XxlJobLogGlue> wrapper = new QueryWrapper<XxlJobLogGlue>().lambda();
        wrapper.eq(XxlJobLogGlue::getJobId, jobId).orderByDesc(XxlJobLogGlue::getId);
        return this.selectList(wrapper);
    }

    default int removeOld(int jobId, @Param("limit") int limit) {
        LambdaQueryWrapper<XxlJobLogGlue> wrapperIn = new QueryWrapper<XxlJobLogGlue>().lambda();
        wrapperIn
            .eq(XxlJobLogGlue::getJobId, jobId)
            .orderByDesc(XxlJobLogGlue::getUpdateTime);
        Page<XxlJobLogGlue> xxlJobLogGluePage = this.selectPage(new Page<XxlJobLogGlue>(0, limit),
            wrapperIn);
        List<XxlJobLogGlue> xxlJobLogGlues = xxlJobLogGluePage.getRecords();
        List<Integer> ids =
            xxlJobLogGlues.stream().map(XxlJobLogGlue::getId).collect(Collectors.toList());
        return this.delete(
            new QueryWrapper<XxlJobLogGlue>()
                .lambda()
                .notIn(XxlJobLogGlue::getId, ids)
                .eq(XxlJobLogGlue::getJobId, jobId));
    }

    default int deleteByJobId(int jobId) {
        return this.delete(
            new QueryWrapper<XxlJobLogGlue>().lambda().eq(XxlJobLogGlue::getJobId, jobId));
    }
}
